package org.fast.develop.logicflow.persistence.domain;

import cn.hutool.core.bean.BeanUtil;
import org.fast.develop.logicflow.persistence.exception.LogicPersistenceException;
import org.fast.develop.logicflow.repository.domain.LogicEntity;
import org.fast.develop.logicflow.repository.domain.LogicRepository;
import org.springframework.data.domain.Example;
import org.springframework.data.jpa.repository.JpaRepository;

import java.io.Serializable;
import java.util.List;
import java.util.Optional;


/**
 * @author 莫寅
 * @createTime 2022-12-20 00:01
 * @desc：
 */
public abstract class BaseLogicRepository<T extends LogicEntity<ID>, ID extends Serializable> implements LogicRepository<T, ID> {

    private JpaRepository<T, ID> jpaRepository;

    public BaseLogicRepository(JpaRepository jpaRepository) {
        this.jpaRepository = jpaRepository;
    }

    abstract protected Class<? extends T> getEntityClass();

    @Override
    public T save(T t) {
        T entityInstance = BeanUtil.copyProperties(t, getEntityClass());
        return jpaRepository.save(entityInstance);
    }

    @Override
    public void delete(ID id) {
        jpaRepository.deleteById(id);
    }

    @Override
    public T get(ID id) {
        return jpaRepository.findById(id)
                .orElseThrow(() -> new LogicPersistenceException("id：{} 的数据不存在！", id));
    }

    @Override
    public T get(T t) {
        T entityInstance = BeanUtil.copyProperties(t, getEntityClass());
        return jpaRepository.findOne(Example.of(entityInstance)).get();
    }

    @Override
    public List<? extends T> getList() {
        return jpaRepository.findAll();
    }

    @Override
    public List<? extends T> getList(T t) {
        T entityInstance = BeanUtil.copyProperties(t, getEntityClass());
        return jpaRepository.findAll(Example.of(entityInstance));
    }

    public JpaRepository<T, ID> getJpaRepository() {
        return jpaRepository;
    }
}
